package com.binarycube.webserver.authenticator;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.log4j.Logger;

import com.binarycube.webserver.config.AuthenticatorConfig;
import com.binarycube.webserver.wrappers.WrappedRequest;

public class LDAPAuthenticator implements IAuthenticator{
	static Logger log = Logger.getLogger(LDAPAuthenticator.class.getName());
	AuthenticatorConfig authenticatorConfig;
	String host, base, port;
		
	
	public LDAPAuthenticator(){
		
	}

	
		
	public void configure(AuthenticatorConfig config) {
		// Get the LDAP detail from the configuration
		 authenticatorConfig = config;
		 host = authenticatorConfig.getProperty("host");
		 port = authenticatorConfig.getProperty("port");
		 base = authenticatorConfig.getProperty("base");
	}


	@Override
	public boolean authenticate(WrappedRequest request) {
		String username = request.getParameter(authenticatorConfig.getUsernameField());
	    String password = request.getParameter(authenticatorConfig.getPasswordField());		
		
	    String uid = "uid=" + username + "," + base;
	    
		Hashtable<String, String> env = new Hashtable<String, String>();
	    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port  );
	    env.put(Context.SECURITY_PRINCIPAL,uid);//UID
	    env.put(Context.SECURITY_CREDENTIALS,password);
	    
	    
		try {
	        LdapContext ctx = new InitialLdapContext(env, null);
	        //Successful
	        return true;
	    } catch (Exception e) {
	    	log.error("Failed login attempt for user: " + username, e);
	    }
		return false;

	}



	@Override
	public String getUID(WrappedRequest wrappedRequest) {
		return wrappedRequest.getParameter(authenticatorConfig.getUsernameField());
	}


	
	
}
